<template>
  <Dialog :title="t('imrStudent.view.title')" v-model="dialogVisible" width="1400">
    <div class="mb-8px" v-hasPermi="['core:imr-student:update']">
      <template v-if="componentsMode === 'view' && !edit">
        <el-button type="primary" plain @click="handleEdit" :disabled="formLoading">
          <Icon icon="ep:edit" />
          {{ t('imrStudent.view.clickEdit') }}
        </el-button>
      </template>
      <template v-else>
        <el-button type="success" plain @click="handleSave" :disabled="formLoading || saveLoading">
          <Icon icon="ep:check" />
          {{ t('imrStudent.view.clickSave') }}
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleCancel"
          :disabled="formLoading || saveLoading"
        >
          <Icon icon="ep:close" />
          {{ t('imrStudent.view.clickCancel') }}
        </el-button>
      </template>
    </div>
    <TabItemImr
      v-if="!formLoading && studentInfo"
      v-model="studentInfo"
      :components-mode="componentsMode"
      v-loading="saveLoading"
    />
    <el-skeleton v-if="formLoading" :rows="5" animated />
    <Dialog :title="t('imrStudent.view.confirmTitle')" v-model="dialogVisibleConfirm" width="1200">
      <ImrStudentInfoDiffView
        ref="diffViewRef"
        v-if="studentInfo && studentInfoBackup"
        :student-info="studentInfo"
        :student-info-backup="studentInfoBackup"
      />
      <el-input
        class="mt-[20px]"
        v-model="modifyComment"
        maxlength="300"
        :placeholder="t('imrStudent.view.modifyPlaceholder')"
        show-word-limit
        type="textarea"
      />
      <template #footer>
        <el-button @click="submitVerify" type="primary" :disabled="verifyLoading"
          >{{ t('common.ok') }}
        </el-button>
        <el-button @click="dialogVisibleConfirm = false">{{ t('common.cancel') }}</el-button>
      </template>
    </Dialog>
  </Dialog>
</template>

<script setup lang="ts">
import TabItemImr from './TabItemImr.vue'
import _ from 'lodash-es'
import ImrStudentInfoDiffView from './ImrStudentInfoDiffView.vue'
import { compareAndFilter } from '@/utils'
import { ImrStudentApi, ImrStudentVO } from '@/api/core/imrstudent'
import { ImrStudentInfoVerifyApi, ImrStudentInfoVerifyVO } from '@/api/core/imrstudentinfoverify'

const { t } = useI18n()

// 修改弹窗备注
const modifyComment = ref('')

const dialogVisible = ref(false)
const dialogVisibleConfirm = ref(false)
const formLoading = ref(false)
const saveLoading = ref(false)
const verifyLoading = ref(false)
const edit = ref(false)

const message = useMessage()

// 弹窗模式 新增数据时=create 查看时=view
const componentsMode = ref('view')

provide('editMode', edit)

const studentInfo = ref<ImrStudentVO>()
const studentInfoBackup = ref<ImrStudentVO>()

const emits = defineEmits(['refresh'])

const getData = async (id: number) => {
  studentInfo.value = await ImrStudentApi.getImrStudent(id)
  studentInfoBackup.value = _.cloneDeep(studentInfo.value)
}

// 重置表单
const resetForm = () => {
  studentInfo.value = {
    id: undefined,
    accountId: undefined,
    studentPhoto: undefined,
    studentCode: undefined,
    studentName: undefined,
    grade: undefined,
    classroom: undefined,
    studentType: undefined,
    inschoolFlag: undefined,
    identityNumber: undefined,
    trainingLevel: undefined,
    primaryMentorId: undefined,
    primaryMentorCode: undefined,
    primaryMentor: undefined,
    researchDeptId: undefined,
    researchDept: undefined,
    originalCollege: undefined,
    gender: undefined,
    birthdate: undefined,
    ethnic: undefined,
    politicalStatus: undefined,
    homeAddress: undefined,
    homeTelephone: undefined,
    personalPhone1: undefined,
    personalEmail1: undefined,
    arpNumber: undefined,
    remark: undefined
  } as unknown as ImrStudentVO
}

/** 打开弹窗 */
const open = async (id: number | null, mode: string) => {
  resetForm()
  componentsMode.value = mode
  edit.value = componentsMode.value !== 'view'
  dialogVisible.value = true
  dialogVisibleConfirm.value = false

  if (id) {
    // 修改时，设置数据
    formLoading.value = true
    try {
      await getData(id)
    } finally {
      formLoading.value = false
    }
  }
}

const handleEdit = () => {
  edit.value = true
}

const handleSave = async () => {
  // 非空校验
  if (studentInfo.value) {
    // 学号
    if (!studentInfo.value.studentCode) {
      message.error(t('common.inputTextPlaceholder') + t('imrStudent.fields.studentCode'))
      return
    }
    // 姓名
    if (!studentInfo.value.studentName) {
      message.error(t('common.inputTextPlaceholder') + t('imrStudent.fields.studentName'))
      return
    }
    // 手机号
    if (!studentInfo.value.personalPhone1) {
      message.error(t('common.inputTextPlaceholder') + t('imrStudent.fields.personalPhone1'))
      return
    }
    // 手机号校验
    if (!/^1\d{10}$/.test(studentInfo.value.personalPhone1)) {
      message.error(t('imrStudent.view.phoneFormatError'))
      return
    }
  }
  if (componentsMode.value === 'view') {
    // 对比保存逻辑
    const newValue = compareAndFilter(studentInfo.value, studentInfoBackup.value)
    // 判断变动是否为{}
    if (_.isEmpty(newValue)) {
      // 没改动 走取消逻辑
      handleCancel()
      return
    }

    modifyComment.value = ''
    // 显示确认弹窗
    dialogVisibleConfirm.value = true
  } else {
    // 新增逻辑
    saveLoading.value = true
    try {
      const data = studentInfo.value as unknown as ImrStudentVO
      const response = await ImrStudentApi.createImrStudent(data)
      message.alertSuccess(
        t('imrStudent.view.createSuccess', {
          username: response.username,
          password: response.password
        })
      )
      dialogVisible.value = false
      // 刷新列表
      emits('refresh')
    } finally {
      saveLoading.value = false
    }
  }
}

const handleCancel = () => {
  edit.value = false
  // 还原可能的更改
  studentInfo.value = _.cloneDeep(studentInfoBackup.value)
}
const diffViewRef = ref<InstanceType<typeof ImrStudentInfoDiffView>>()
const submitVerify = async () => {
  verifyLoading.value = true
  const data: Partial<ImrStudentInfoVerifyVO> = {
    accountId: studentInfoBackup.value?.accountId,
    studentCode: studentInfoBackup.value?.studentCode,
    studentName: studentInfoBackup.value?.studentName,
    studentGrade: studentInfoBackup.value?.grade,
    studentClass: studentInfoBackup.value?.classroom,
    verifyType: '管理员修改',
    verifyStatus: '待审核',
    modifyFields: diffViewRef.value?.getModifyField() ?? '',
    oldValue: JSON.stringify(studentInfoBackup.value),
    newValue: JSON.stringify(studentInfo.value),
    remark: modifyComment.value
  }
  try {
    await ImrStudentInfoVerifyApi.adminModifyImrStudent(data)
    dialogVisibleConfirm.value = false
    dialogVisible.value = false
    // 刷新列表
    emits('refresh')
    message.success(t('common.updateSuccess'))
  } finally {
    verifyLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped lang="scss"></style>
